package td.domain;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.TreeSet;

import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Window;

public class DemoStore {

	private static DemoStore db;

	public static DemoStore db() {
		if (db == null) {
			db = new DemoStore();
		}
		return db;
	}

	HashMap<String, Thinker> thinkers = new HashMap<String, Thinker>();
	HashMap<Long, Thinker> thinkersById = new HashMap<Long, Thinker>();

	HashMap<String, Category> categories = new HashMap<String, Category>();
	public ArrayList<Category> allCategoryList = new ArrayList<Category>();

	HashMap<Long, TagDef> tags = new HashMap<Long, TagDef>();
	public ArrayList<TagDef> allTagList = new ArrayList<TagDef>();

	HashMap<Long, ArrayList<Tag>> tagInstances = new HashMap<Long, ArrayList<Tag>>();

	public ArrayList<Thought> allThoughtList = new ArrayList<Thought>();

	public HashMap<String, Topic> topics = new HashMap<String, Topic>();

	public ArrayList<Topic> allTopicList = new ArrayList<Topic>();

	Thinker joeSixpack;
	Thinker johnSmith;
	Thinker jamesJohnson;
	HashMap<Long, Thought> thoughts = new HashMap<Long, Thought>();
	public Category rootCategory;
	public TagDef rootTag;
	private Date now = new Date();

	private Comparator<Thought> newFirstComparator = new Comparator<Thought>() {

		@Override
		public int compare(Thought thought1, Thought thought2) {
			if (thought1.getPublishedDate().before(thought2.getPublishedDate())) {
				return -1;
			}
			return 1;
		}
	};

	public DemoStore() {
		createCategories();
		createTags();
		createThinkers();
		createThoughts();
		reorder(rootCategory);
		reorder(rootTag);
	}

	public HashMap<String, Thinker> getThinkers() {
		return this.thinkers;
	}

	public HashMap<Long, Thinker> getThinkersById() {
		return thinkersById;
	}

	public <H extends Hierarchy<H>> void reorder(H hierarchy) {
		ArrayList<H> children = hierarchy.getChildren();
		if (children == null || children.size() < 2) {
			return;
		}
		for (H child : children) {
			reorder(child);
		}
		java.util.Collections.sort(children);
	}

	public <S extends Statistical> List<S> reorder(List<S> statsList) {
		java.util.Collections.sort(statsList);
		return statsList;
	}

	private void createThoughts() {
		addThought(
				"Hamburg",
				"We got stuck in Hamburg for one night and stumbled into a concert :)",
				"Hamburg ( /ˈhæmbɜrɡ/; German pronunciation: [ˈhambʊɐ̯k], local pronunciation [ˈhambʊɪç]; Low German/Low Saxon: Hamborg [ˈhaˑmbɔːx]), officially Free and Hanseatic City of Hamburg, is the second largest city in Germany, the fifteenth largest German state, and the sixth largest city in the European Union.[2] The city is home to over 1.8 million people, while the Hamburg Metropolitan Region (including parts of the neighbouring Federal States of Lower Saxony and Schleswig-Holstein) has more than 5 million inhabitants. Situated on the river Elbe, the port of Hamburg is the third largest port in Europe (after the Port of Rotterdam and Port of Antwerp) and tenth largest worldwide.",
				joeSixpack, "Germany", "Travel Light", 3);
		addThought(
				"Cologne",
				"Best hostle ever, cathedal and the bridge.",
				"Cologne (English pronunciation: /kəˈloʊn/, German: Köln [kœln], Kölsch: Kölle [ˈkœɫə]) is Germany's fourth-largest city (after Berlin, Hamburg and Munich), and is the largest city both in the German Federal State of North Rhine-Westphalia and within the Rhine-Ruhr Metropolitan Area, one of the major European metropolitan areas with more than ten million inhabitants.<br/><br/>"
						+ "Cologne is located on both sides of the Rhine River. The city's famous Cologne Cathedral (Kölner Dom) is the seat of the Catholic Archbishop of Cologne. The University of Cologne (Universität zu Köln) is one of Europe's oldest and largest universities.[2]",
				jamesJohnson, "Germany", "Travel Light", 4);
		addThought(
				"Berlin",
				"Man what a historic and fun city!",
				"Berlin ( /bɜrˈlɪn/; German pronunciation: [bɛɐ̯ˈliːn] ( listen)) is the capital city of Germany and one of the 16 states of Germany. With a population of 3.5 million people,[1] Berlin is Germany's largest city and is the second most populous city proper and the seventh most populous urban area in the European Union.[4] Located in northeastern Germany on the River Spree, it is the center of the Berlin-Brandenburg Metropolitan Region, which has 6 million residents from over 180 nations.[5][6] Due to its location in the European Plains, Berlin is influenced by a temperate seasonal climate. Around one third of the city's area is composed of forests, parks, gardens, rivers and lakes.[7]<br/><br/>"
						+ "First documented in the 13th century, Berlin was the capital of the Kingdom of Prussia (1701–1918), the German Empire (1871–1918), the Weimar Republic (1919–1933) and the Third Reich (1933–1945).[8] Berlin in the 1920s was the third largest municipality in the world.[9] After World War II, the city became divided into East Berlin—the capital of East Germany—and West Berlin, a West German exclave surrounded by the Berlin Wall from 1961–1989.[10] Following German reunification in 1990, the city regained its status as the capital of Germany, hosting 147 foreign embassies.[11][12]<br/><br/>"
						+ "Berlin is a world city of culture, politics, media, and science.[13][14][15] Its economy is primarily based on the service sector, encompassing a diverse range of creative industries, media corporations, and convention venues. Berlin also serves as a continental hub for air and rail transport,[16][17] and is a popular tourist destination.[18] Significant industries include IT, pharmaceuticals, biomedical engineering, biotechnology, electronics, traffic engineering, and renewable energy.<br/><br/>"
						+ "Berlin is home to renowned universities, research institutes, orchestras, museums, and celebrities, as well as host of many sporting events.[19] Its urban settings and historical legacy have made it a popular location for international film productions.[20] The city is well known for its festivals, diverse architecture, nightlife, contemporary arts, public transportation networks and a high quality of living.[21]",
				joeSixpack, "Germany", "Travel Light", 10);
		addThought(
				"Trier",
				"Oldest City in Germany, Roman Ruins & Karl Marx",
				"Trier (German pronunciation: [ˈtʀiːɐ̯] ( listen); French: Trèves, IPA: [tʁɛv]; Luxembourgish: Tréier; Italian: Treviri; Latin: Augusta Treverorum; the Latin adjective associated with the city is Treverensis), historically called in English Treves, is a city in Germany on the banks of the Moselle. It is the oldest city in Germany, founded in or before 16 BC.[2]<br/><br/>"
						+ "Trier lies in a valley between low vine-covered hills of ruddy sandstone in the west of the state of Rhineland-Palatinate, near the border with Luxembourg and within the important Mosel wine region.",
				johnSmith, "Germany", "Travel Smart", 2);
		addThought(
				"Rhein & Mosel",
				"Castles, festivals and wine",
				"Mosel is one of 13 German wine regions (Weinbaugebiete) for quality wines (QbA and Prädikatswein), and takes its name from the Moselle River (German: Mosel). Before 1 August 2007 the region was called Mosel-Saar-Ruwer, but changed to a name that was considered more consumer-friendly.[1][2] The wine region is Germany's third largest in terms of production but is the leading region in terms of international prestige.",
				jamesJohnson, "Germany", "Travel Smart", 4);
		addThought(
				"Munich and surrondings",
				"History, Architecture and Beer",
				"Munich ( /ˈmjuːnɪk/; German: München, pronounced [ˈmʏnçən] ( listen)[2], Bavarian: Minga) is the capital and the largest city of the German state of Bavaria. It is located on the River Isar north of the Bavarian Alps. Munich is the third largest city in Germany, behind Berlin and Hamburg. About 1.42 million people live within the city limits. Munich was the host city of the 1972 Summer Olympics.<br/><br/>"
						+ "The city's motto is \"München mag Dich\" (Munich likes you). Before 2006, it was \"Weltstadt mit Herz\" (Cosmopolitan city with a heart). Its native name, München, is derived from the Old High German Munichen, meaning \"by the monks' place\". The city's name derives from the monks of the Benedictine order who founded the city; hence the monk depicted on the city's coat of arms. Black and gold—the colours of the Holy Roman Empire—have been the city's official colours since the time of Ludwig the Bavarian.",
				joeSixpack, "Germany", "Travel Smart", 15);
		addThought(
				"Tubingen",
				"University Ties and Winter Festival",
				"Tübingen (help·info) is a traditional university town in central Baden-Württemberg, Germany. It is situated 30 km (19 mi) south of the state capital, Stuttgart, on a ridge between the Neckar and Ammer rivers. About one in ten people living in Tübingen is a student.",
				jamesJohnson, "Germany", "Travel With a smile", 2);
		addThought(
				"Wurzburg",
				"The Residence and the wine festival",
				"Würzburg (German pronunciation: [ˈvʏɐ̯tsbʊɐ̯k]; Main-Franconian: Wörtzburch) is a city in the region of Franconia, Northern Bavaria, Germany. Located on the Main River, it is the capital of the Regierungsbezirk Lower Franconia. The regional dialect is Franconian.<br/><br/>"
						+ "The Würzburg Residence (German: Würzburger Residenz) is a palace in Würzburg, southern Germany. Johann Lukas von Hildebrandt and Maximilian von Welsch, representants of the Austrian/South German Baroque were involved in the construction, as well as Robert de Cotte and Germain Boffrand, who were followers of the French Style. Balthasar Neumann, architect of the court of the Bishop of Würzburg, was the principal architect of the Residenz, which was commissioned by the Prince-Bishop of Würzburg Johann Philipp Franz von Schönborn and his brother Friedrich Carl von Schönborn in 1720, and completed in 1744. The Venetian painter Giovanni Battista Tiepolo, assisted by his son, Domenico, painted frescoes in the building.",
				johnSmith, "Germany", "Travel With a smile", 3);
		addThought(
				"Rothenburg ob der Tauber",
				"Beautiful? Yes! Tourist Trap? Yes!!!",
				"Rothenburg ob der Tauber (German pronunciation: [ˈʁoːtənbʊɐ̯k ɔp deːɐ̯ ˈtaʊbɐ] ( listen)) is a town in the district of Ansbach of Mittelfranken (Middle Franconia), the Franconia region of Bavaria, Germany, well known for its well-preserved medieval old town, a destination for tourists from around the world. Rothenburg was a Free Imperial City from the late Middle Ages to 1803.",
				joeSixpack, "Germany", "Travel With a smile", 10);
		addThought(
				"Rome",
				"All roads lead to Rome",
				"Rome (/ˈroʊm/; Italian: Roma pronounced [ˈroːma] ( listen); Latin: Rōma) is a city and special comune (\"Roma Capitale\") in Italy. Rome is the capital of Italy and the capital of Lazio (Latin: Latium). With 2.8 million residents in 1,285.3 km2 (496.3 sq mi), it is also the country's largest and most populated comune and fourth-most populous city in the European Union by population within city limits. Between 3.2 and 3.8 million people live in the Rome urban and metropolitan area.[3][4][5][6][7][8] The city is located in the central-western portion of the Italian Peninsula, on the Tiber River within the Lazio region of Italy. Rome is referred to as \"The Eternal City\", a notion expressed by ancient Roman poets and writers.<br/><br/>"
						+ "Rome's history spans more than two and a half thousand years, since its founding in 753 BC, with the union of rural villages. It was the capital city of the Roman Kingdom, the Roman Republic and the Roman Empire, which was the dominant power in Western Europe and the lands bordering the Mediterranean for over seven hundred years from the 1st century BC until the 7th century AD and the city is regarded as one of the birthplaces of western civilization. Since the 1st century AD Rome has been the seat of the Papacy and, after the end of Byzantine domination, in the 8th century it became the capital of the Papal States, which lasted until 1870. In 1871 Rome became the capital of the Kingdom of Italy, and in 1946 that of the Italian Republic.<br/><br/>"
						+ "After the Middle Ages, Rome was ruled by popes such as Alexander VI and Leo X, who transformed the city into one of the major centers of the Italian Renaissance, along with Florence.[9] The current version of St Peter's Basilica was built and the Sistine Chapel was painted by Michelangelo. Famous artists and architects, such as Bramante, Bernini and Raphael resided for some time in Rome, contributing to its Renaissance and Baroque architecture.",
				jamesJohnson, "Italy", "Travel Fun", 20);
		addThought(
				"Venice",
				"Need I say more?",
				"Venice (Italian: Venezia [veˈnɛttsja] ( listen), Venetian: Venexia [veˈnɛsja]; (Latin: Venetia) is a city in northeast Italy sited on a group of 118 small islands separated by canals and linked by bridges.[1] It is located in the marshy Venetian Lagoon which stretches along the shoreline between the mouths of the Po and the Piave Rivers. Venice is renowned for the beauty of its setting, its architecture and its artworks.[1] The city in its entirety is listed as a World Heritage Site, along with its lagoon.[1].<br/><br/>"
						+ "Venice is the capital of the Veneto region. In 2009, there were 270,098 people residing in Venice's comune (the population estimate of 272,000 inhabitants includes the population of the whole Comune of Venezia; around 60,000[2] in the historic city of Venice (Centro storico); 176,000 in Terraferma (the Mainland), mostly in the large frazioni of Mestre and Marghera; 31,000 live on other islands in the lagoon). Together with Padua and Treviso, the city is included in the Padua-Treviso-Venice Metropolitan Area (PATREVE) (population 1,600,000).",
				johnSmith, "Italy", "Travel Fun", 30);
		addThought(
				"Florence",
				"Art overload, needed more time to really take it all in.",
				"Florence (Italian: Firenze [fiˈrɛntse] ( listen), alternative obsolete form: Fiorenza; Latin: Florentia) is the capital city of the Italian region of Tuscany and of the province of Florence. It is the most populous city in Tuscany, with approximately 370,000 inhabitants, expanding to over 1.5 million in the metropolitan area.[2]<br/><br/>"
						+ "Florence is famous for its history. A centre of medieval European trade and finance and one of the wealthiest cities of the time,[3] Florence is considered the birthplace of the Renaissance, and has been called the Athens of the Middle Ages.[4] A turbulent political history includes periods of rule by the powerful Medici family, and numerous religious and republican revolutions. From 1865 to 1870 the city was also the capital of the recently established Kingdom of Italy.",
				joeSixpack, "Italy", "Travel Fun", 16);
		addThought(
				"Pisa",
				"Yes it really is leaning THAT much",
				"Pisa ( /ˈpiːzə/; Italian pronunciation: [ˈpiːsa][1]) is a city in Tuscany, Central Italy, on the right bank of the mouth of the River Arno on the Tyrrhenian Sea. It is the capital city of the Province of Pisa. Although Pisa is known worldwide for its leaning tower (the bell tower of the city's cathedral), the city of over 88,332 residents (around 200,000 with the metropolitan area) contains more than 20 other historic churches, several palaces and various bridges across the River Arno.",
				jamesJohnson, "Italy", "Travel Fun", 10);
		addThought(
				"Cinque Terre",
				"Hiker's paradise",
				"The Cinque Terre (Italian pronunciation: [ˌtʃinkwe ˈtɛrːe]) is a rugged portion of coast on the Italian Riviera. It is in the Liguria region of Italy, to the west of the city of La Spezia. \"The Five Lands\" is composed of five villages: Monterosso al Mare, Vernazza, Corniglia, Manarola, and Riomaggiore. The coastline, the five villages, and the surrounding hillsides are all part of the Cinque Terre National Park and is a UNESCO World Heritage Site.",
				johnSmith, "Italy", "Travel Fun", 5);
		addThought(
				"Barcelona",
				"How to see Barcelona? With friends!",
				"Barcelona (English /bɑrsɨˈloʊnə/, Catalan: [bərsəˈɫonə], Spanish: [barθeˈlona]) is the capital of Catalonia and the second largest city in Spain, after Madrid, with a population of 1,621,537 within its administrative limits on a land area of 101.4 km2 (39 sq mi). The urban area of Barcelona extends beyond the administrative city limits with a population of between 4,200,000[1] and 4,500,000[2] within an area of 803 km2 (310 sq mi),[1] being the sixth-most populous urban area in the European Union after Paris, London, the Ruhr, Madrid and Milan. About five million[3][4][5][6] people live in the Barcelona metropolitan area. It is also the largest metropolis on the Mediterranean Sea. It is located on the Mediterranean coast between the mouths of the rivers Llobregat and Besòs and is bounded to the west by the Serra de Collserola ridge (512 m/1,680 ft).",
				joeSixpack, "Iberian Peninsula", "Still Traveling", 10);
		addThought(
				"Madrid",
				"Walk, eat, ride out to the country side.",
				"Madrid (English /məˈdrɪd/, Spanish: [maˈðɾið]) is the capital and largest city of Spain. The population of the city is roughly 3.3 million[4] and the entire population of the Madrid metropolitan area is calculated to be 6.5 million.[5] It is the third-largest city in the European Union, after London and Berlin, and its metropolitan area is the third-largest in the European Union after London and Paris.[6][7][8][9] The city spans a total of 604.3 km2 (233.3 sq mi).[10]",
				johnSmith, "Iberian Peninsula", "Still Traveling", 9);
		addThought(
				"Lisbon",
				"Moorish Castle and new Czech/Lybian friends",
				"Lisbon (/ˈlɪzbən/; Portuguese: Lisboa, IPA: [ɫiʒˈboɐ][1]) is the capital city and largest city of Portugal with a population of 547,631 within its administrative limits[2] on a land area of 84.8 km2 (33 sq mi). The urban area of Lisbon extends beyond the administrative city limits with a population of over 3 million[3] on an area of 958 km2 (370 sq mi),[3] making it the 9th most populous urban area in the European Union. About 2,831,000[4][5] people live in the Lisbon Metropolitan Area (which represents approximately 27% of the population of the country). Lisbon is the westernmost large city located in Europe, as well as its westernmost capital city and the only one along the Atlantic coast. It lies in the western Iberian Peninsula on the Atlantic Ocean and the Tagus River.",
				jamesJohnson, "Iberian Peninsula", "Still Traveling", 7);
		addThought(
				"Salema and the area",
				"The best way to get lost in South Portugal!",
				"Salema is a village located near Vila do Bispo in the Algarve, Portugal. Historically it was a fishing village, but it is now a popular tourist destination.",
				joeSixpack, "Iberian Peninsula", "Travel Always", 1);
		addThought(
				"Seville",
				"Scorching weather in October, ditch the trains to see the country side, Flamenco!",
				"Seville ( /səˈvɪl/; Spanish: Sevilla, IPA: [seˈβiʎa], locally: [seˈβiʝa]) is the capital of the autonomous community of Andalusia and the province of Seville, Spain. It is situated on the plain of the River Guadalquivir. The inhabitants of the city are known as sevillanos (feminine form: sevillanas) or hispalenses, after the Roman name of the city, Hispalis. Seville has a municipal population of about 703,000 as of 2011, and a metropolitan population of about 1.2 million, making it the fourth-largest city in Spain and the 31st most populous municipality in the European Union. Its Old Town, the third largest in Europe with an area of 4km², contains three UNESCO World Heritage Sites: the Alcázar palace complex, the Cathedral and the General Archive of the Indies. The Seville harbour, located about 80 km from the Atlantic Ocean, is the only river port in Spain.",
				johnSmith, "Iberian Peninsula", "Travel Always", 7);
		addThought(
				"Acapulco",
				"Saw the divers, partied it up, but would have never seen the coutry side without friends.",
				"Acapulco (officially known as Acapulco de Juárez) is a city, municipality and major sea port in the state of Guerrero on the Pacific coast of Mexico, 300 kilometres (190 mi) southwest from Mexico City. Acapulco is located on a deep, semi-circular bay and has been a port since the early colonial period of Mexico’s history.[1] It is a port of call for shipping and cruising lines running between Panama and San Francisco, California, United States.[2] The city of Acapulco is the largest in the state, far larger than the state capital Chilpancingo. Acapulco is also Mexico's largest beach and balneario resorted city.[3]",
				jamesJohnson, "Mexico", "Siempre Viajar", 4);
		addThought(
				"Tulum",
				"Why go to Cancun when you can hang in the village",
				"Tulum (Yucatec: Tulu'um) is the site of a Pre-Columbian Maya walled city serving as a major port for Cobá.[1] The ruins are situated on 12-meter (39 ft) tall cliffs, along the east coast of the Yucatán Peninsula on the Caribbean Sea in the state of Quintana Roo, Mexico.[1] Tulum was one of the last cities inhabited and built by the Mayans, it was at its height between the 13th and 15th centuries and managed to survive about 70 years after the Spanish began occupying Mexico. Old World diseases brought by the Spanish settlers appear to have been the cause of its demise. One of the best-preserved coastal Maya sites, Tulum is today a popular site for tourists.[1]",
				johnSmith, "Mexico", "Siempre Viajar", 50);

		addThought(
				"My family is ... interesting ...",
				"In human context, a family (from Latin: familia) is a group of people affiliated by consanguinity, affinity, or co-residence. In most societies it is the principal institution for the socialization of children.",
				" Anthropologists most generally classify family organization as matrilocal (a mother and her children); conjugal (a wife, husband, and children, also called nuclear family); and consanguinal (also called an extended family) in which parents and children co-reside with other members of one parent's family.<br/><br/>"
						+ "There are also concepts of family that break with tradition within particular societies, or those that are transplanted via migration to flourish or else cease within their new societies.[clarification needed] As a unit of socialization the family is the object of analysis for sociologists of the family. Genealogy is a field which aims to trace family lineages through history. In science, the term \"family\" has come to be used as a means to classify groups of objects as being closely and exclusively related. In the study of animals it has been found that many species form groups that have similarities to human \"family\"—often called \"packs.\" Sexual relations among family members are regulated by rules concerning incest such as the incest taboo.",
				joeSixpack, "Starting A Family", "Families Rule");
		addThought(
				"How I proposed",
				"A marriage proposal is an event where one person in a relationship asks for the other's hand in marriage. If accepted, it marks the initiation of engagement. ",
				"It often has a ritual quality, sometimes involving the presentation of an engagement ring and the formal asking of a question such as, \"Will you marry me?\" In western culture, it is traditional for the man to propose to the woman while kneeling on one knee before her (occasionally referred to as genuflection), and sometimes putting the ring on her finger, as opposed to merely giving it to her. Often the proposal is a surprise.<BR/><BR/>"
						+ "The average duration of preceding courtship varies considerably throughout the world. (See courtship duration.)",
				johnSmith, "Proposing", "Now and forever");

		addThought(
				"Are you ready for a baby?",
				"Pregnancy is one of the biggest physical changes your body will ever undergo, so before you start trying, make sure you're in the best possible condition. Dads-to-be may have some work to do, too: What you eat, drink, and otherwise ingest can affect the quality of your sperm. Take our quiz to see if you're both physically ready for baby-making.",
				"WShould I see my GP before I try to get pregnant?<br/>"
						+ "What can I expect at a pre-pregnancy check-up?<br/>"
						+ "Will I need any medical tests?<br/>"
						+ "Should I have any vaccinations before trying for a baby?<br/>"
						+ "Should I take any pre-pregnancy supplements?<br/>"
						+ "What about smoking, drinking or taking drugs? Can my GP help with giving up?<br/>"
						+ "Giving your baby the best start in life means getting your own health sorted well before you become pregnant. Your general wellbeing, and any medication you're taking, can all affect your chances of having a healthy pregnancy.",
				joeSixpack, "Getting ready for children", "Get it done");
		addThought(
				"Child development",
				"Child development refers to the biological and psychological and emotional changes that occur in human beings between birth and the end of adolescence, as the individual progresses from dependency to increasing autonomy.",
				"Because these developmental changes may be strongly influenced by genetic factors and events during prenatal life, genetics and prenatal development are usually included as part of the study of child development. Related terms include developmental psychology, referring to development throughout the lifespan, and pediatrics, the branch of medicine relating to the care of children. Developmental change may occur as a result of genetically-controlled processes known as maturation, or as a result of environmental factors and learning, but most commonly involves an interaction between the two. It may also occur as a result of human nature and our ability to learn from our environment. Human beings have a keen sense to adapt to their surroundings and this is what child development encompasses. Every child would struggle to find their culture and identity in child development.",
				jamesJohnson, "Child Development", "Tired but Happy");

		addThought(
				"My husband is the coolest!",
				"A husband is a male lifetime partner in a marital relationship. The rights and obligations of the husband regarding his spouse and others, and his status in the community and in law, vary between cultures and has varied over time. In a heterosexual relationship, a man's spouse would be his wife.",
				"At the conclusion of a valid wedding, the marrying parties acquire the status of married person and, while the marriage persists, a man is called a husband, whereas a woman is called a wife. Married people are the spouse of the person they married.<br/><br/>"
						+ "Although \"husband\" is a close term to groom, the latter is a male participant in a wedding ceremony, while a husband is a married man after the wedding, during his marriage. The term husband refers to the institutionalized role of the married male, while the term father refers to the male in context of his offspring, a state which may or may not indicate that a marriage ceremony has taken place.",
				johnSmith, "Husbands", "Do it now");
		addThought(
				"Love my wife! She's Hot, Smart and Family Oriented!",
				"A wife is a female lifetime partner in a continuing marital relationship. A wife may also be referred to as a spouse. ",
				"The term continues to be applied to a woman who has separated from her husband and ceases to be applied to such a woman only when her marriage has come to an end following a legally recognised divorce or the death of her spouse. The rights and obligations of the wife in relation to her husband and others, and her status in the community and in law, varies between cultures and has varied over time. In a heterosexual relationship, a woman's spouse is her husband.<br/><br/>"
						+ "The term is most commonly applied to a woman in a legally sanctioned marriage, and not to a woman in another cohabitation relationship such as a concubine, mistress etc. However, a woman in a so-called common law marriage may describe herself as a common law wife, de facto wife, or simply a wife; but sometimes the female is described as \"girlfriend\" or \"partner\". Those seeking to advance gender neutrality may refer to both marriage partners as \"spouses\", and many countries are rewording their statute law by replacing \"wife\" and \"husband\" with \"spouse\". Also, in a polygamous marriage, each woman is described as a wife.",
				johnSmith, "Wifes", "Learn to listen");

		addThought(
				"Why are me and my sister so different?",
				"Today is my sister’s birthday. Like my dad, my big sister has taught me a thing or two over the years.",
				"Despite her deep-seated belief that she’s not good at math, my sister is very, very good at math, especially when it comes to money. So whenever I have a financial question, I turn to her for help. Should I put extra money that I made towards my RRSPs or towards paying off my student loans? “Do a spreadsheet and figure out what gives you better results. Numbers don’t lie, Beth,” she’ll say. Similarly, despite knowing, logically, that buying real estate right now is a terrible, terrible idea, there is that piece of me that feels like “you are a giant failure if you don’t own any property!” To which she’ll say, “Keep your emotions out of it. Make a pros and cons list and see how you can get what you want from buying property in ways other than buying property. And do a spreadsheet – numbers don’t lie!”",
				johnSmith, "Sisters", "Don't dis");
		addThought(
				"I want to be like my brother!",
				"Brother is male having the same parents as another or one parent in common with another.",
				"Go bro!", jamesJohnson, "Brothers", "Comrades forever!");

		addThought(
				"It takes an effort to get along with your parents!",
				"A parent (from Latin: parēns = parent) is a caretaker of the offspring in their own species.",
				"In humans, a parent is of a child (where \"child\" refers to offspring, not necessarily age). Children can have one or more parents, but they must have two biological parents. Biological parents consist of the male who sired the child and the female who gave birth to the child. In all human societies, the biological mother and father are both responsible for raising their young. However, some parents may not be biologically related to their children. An adoptive parent is one who nurtures and raises the offspring of the biological parents but is not actually biologically related to the child. Children without adoptive parents can be raised by their grandparents or other family members.",
				joeSixpack, "My Parents", "Respect");
		addThought(
				"My grandpa was the coolest!",
				"Grandparents are the parents of a person's own parent, whether that be a father or a mother.",
				"Every sexually-reproducing creature who is not a genetic chimera has a maximum of four genetic grandparents, eight genetic great-grandparents, sixteen genetic great-great-grandparents, etc. Rarely, such as in the case of sibling or half-sibling incest, these numbers are lower. In the history of modern humanity, around 30,000 years ago, the number of modern humans who lived to be grandparents began to skyrocket. It is not known for certain what spurred this increase in longevity. But it is believed that a key consequence of three generations being alive together was the facilitation of the passing along of information that prior to that point would have been lost; an example of this important information might have been where to find water in times of drought.",
				johnSmith, "My Grandparents", "Lots of Respect");
		addThought(
				"I like my parents in law",
				"A parent-in-law is a person who has a legal affinity with another by being the parent of the other's spouse.",
				"Many cultures and legal systems impose duties and responsibilities on persons connected by this relationship. A person is a son-in-law or daughter-in-law to the parents of the spouse, who are in turn also the parents of those sisters-in-law and brothers-in-law (if any) who are siblings of the spouse (as opposed to spouses of siblings). Together the members of this family affinity group are called the in-laws.",
				jamesJohnson, "Parents-In-Law", "More Respect");

		addThought(
				"My Cousin is in China right now!",
				"In kinship terminology, a cousin is a relative with whom a person shares one or more common ancestor(s) (other than a parent, child/descendant, sibling, child/descendant of a sibling, or sibling of a parent/ancestor). However in common parlance, \"cousin\" normally specifically means \"first cousin\".",
				"Systems of \"degrees\" and \"removals\" are used in the English-speaking world to describe the exact relationship between two cousins (in the broad sense) and the ancestor they have in common. Various governmental entities have established systems for legal use that can more precisely specify kinships with common ancestors existing any number of generations in the past, though common usage often eliminates the degrees and removals and refers to people with common ancestry as simply \"distant cousins\" or \"relatives\".",
				jamesJohnson, "Cousins", "One big family");
		addThought(
				"Niece that I don't know.",
				"My sister lives far way so I don't contribute enough in development of my niece :(",
				"A nephew is a son of one's sibling, sibling-in-law, or half-sibling, and a niece is a daughter of one's sibling, sibling-in-law, or half-sibling. Sons and daughters of siblings-in-law are also informally referred to as nephews and nieces respectively, even though there is no blood relation. The word nephew is derived from the French word neveu.",
				joeSixpack, "Nieces and Nephews", "Like sons and dauthers");
		addThought(
				"My uncle loves the Beatles.",
				"He's just a really cool guy overall.",
				"Uncle (from Latin: avunculus \"little grandfather\", the diminutive of avus \"grandfather\",) is a family relationship or kinship, between a person and his or her parent's brother or parent's brother-in-law.",
				johnSmith, "Aunts and Uncles", "Don't forget");

		addThought(
				"This class rules!",
				"I've learned so much in this class and gained a real appreciating for GUIs.",
				"Human–computer Interaction (HCI) involves the study, planning, and design of the interaction between people (users) and computers. It is often regarded as the intersection of computer science, behavioral sciences, design and several other fields of study. The term was popularized by Card, Moran, and Newell in their seminal 1983 book, \"The Psychology of Human-Computer Interaction\", although the authors first used the term in 1980[1], and the first known use was in 1975[2]. The term connotes that, unlike other tools with only limited uses (such as a hammer, useful for driving nails, but not much else), a computer has many affordances for use and this takes place in an open-ended dialog between the user and the computer.",
				jamesJohnson, "Human Computer Interaction", "Useful things");
		addThought(
				"Why I need to work on my drawing skills",
				"Eventually this site will have to use graphics, to some extent at least.",
				"Graphic design is a creative process—most often involving a client and a designer and usually completed in conjunction with producers of form (i.e., printers, signmakers, etc.)—undertaken in order to convey a specific message (or messages) to a targeted audience. The term \"graphic design\" can also refer to a number of artistic and professional disciplines that focus on visual communication and presentation. The field as a whole is also often referred to as Visual Communication or Communication Design. Various methods are used to create and combine words, symbols, and images to create a visual representation of ideas and messages. A graphic designer may use a combination of typography, visual arts and page layout techniques to produce the final result. Graphic design often refers to both the process (designing) by which the communication is created and the products (designs) which are generated.",
				joeSixpack, "Graphics Design", "Pretty things");

		addThought(
				"Broncos just won 3rd in a row.",
				"Manning kicked butt as usual and defence is looking better and better every game.",
				"American football, known in the United States simply as football, is a sport played between two teams of eleven with the objective of scoring points by advancing the ball into the opposing team's end zone by running with it or throwing it to a teammate. Points can be scored by carrying the ball over the opponent's goal line, catching a pass thrown over that goal line, kicking the ball through the opponent's goal posts or tackling an opposing ball carrier in his own end zone.",
				johnSmith, "American Football", "Brute Force");
		addThought(
				"Still can believe Mexico beat Brazil in Olympics",
				"And South Korea in 3rd? Wow!",
				"Association football, commonly known as football or soccer, is a sport played between two teams of eleven players with a spherical ball. At the turn of the 21st century, the game was played by over 250 million players in over 200 countries, making it the world's most popular sport.[1][2][3][4] The game is played on a rectangular field of grass or green artificial turf, with a goal in the middle of each of the short ends. The object of the game is to score by driving the ball into the opposing goal.",
				jamesJohnson, "Soccer", "Some finesse");

		addThought(
				"I think America is doing pretty well, in comparison...",
				"I mean look at Euro-zone, now those guys got problems! Just gotta create those jobs, man!",
				"Economics is the social science that analyzes the production, distribution, and consumption of goods and services. The term economics comes from the Ancient Greek οἰκονομία (oikonomia, \"management of a household, administration\") from οἶκος (oikos, \"house\") + νόμος (nomos, \"custom\" or \"law\"), hence \"rules of the house(hold)\".[1] Political economy was the earlier name for the subject, but economists in the late 19th century suggested 'economics' as a shorter term for 'economic science' that also avoided a narrow political-interest connotation and as similar in form to 'mathematics', 'ethics', and so forth.",
				joeSixpack, "Economics", "Fun science");
		addThought(
				"I love America, no matter who wins the elections",
				"In fact, one of the reasons I love it is because it's so stable.  I mean there isn't going to be a revolution no matter who is the president, right?",
				"Politics (from Greek politikos \"of, for, or relating to citizens\") as a term is generally applied to the art or science of running governmental or state affairs, including behavior within civil governments, but also applies to institutions, fields, and special interest groups such as the corporate, academic, and religious segments of society. It consists of \"social relations involving authority or power\" and to the methods and tactics used to formulate and apply policy.[1]<br/><br/>"
						+ "Modern political discourse focuses on democracy and the relationship between people and politics. It is thought of as the way we \"choose government officials and make decisions about public policy\".",
				johnSmith, "Politics", "Talk science");

		addThought(
				"I really gotta beef up on my classics",
				"I took an intro class about 2 years ago and already I can't remeber anything!",
				"Philosophy is the study of general and fundamental problems, such as those connected with reality, existence, knowledge, values, reason, mind, and language.[1][2] Philosophy is distinguished from other ways of addressing such problems by its critical, generally systematic approach and its reliance on rational argument.[3] The word \"philosophy\" comes from the Greek φιλοσοφία (philosophia), which literally means \"love of wisdom\".[4][5][6] In more casual speech the \"philosophy\" of a particular person can refer to the beliefs held by that person.",
				joeSixpack, "Philosophy", "BS science");
		addThought(
				"I don't watch many movies but Looper was great!",
				"I think its the second movie I saw this year so not much of a comparison, but I really liked it.",
				"Looper is a 2012 American science fiction action film written and directed by Rian Johnson. The film stars Bruce Willis, Joseph Gordon-Levitt, and Emily Blunt. In Looper, time travel is invented by the year 2074 and, though immediately outlawed, is used by criminal organizations to send those they want killed into the past where they are killed by \"loopers\", assassins paid with silver bars strapped to their targets. Joe, a looper, encounters himself when his older self is sent back in time to be killed. The film deals with themes of time alteration, age, love, crime, and parenthood.<br/><br/>"
						+ "Looper was selected as the opening film of the 2012 Toronto International Film Festival.",
				johnSmith, "Movies", "Entertainment");
		addThought(
				"I'm not much of a shoper but groceries are different.",
				"Buying groceries, especially produce has become very rewarding to me.",
				"A retailer or shop is a business that presents a selection of goods or services and offers to sell them to customers for money or other goods. Shopping is an activity in which a customer browses the available goods or services presented by one or more retailers with the intent to purchase a suitable selection of them. In some contexts it may be considered a leisure activity as well as an economic one.",
				johnSmith, "Shopping", "Why we need different clothing");

	}

	public void addRead(Thought thought, Thinker thinker) {
		// Update thinker's read history
		if (thinker != null) {
			if (thought.getThinkerId().equals(thinker.getId())) {
				// Thought belongs to this thinker, so it's not 'true' read
				// TODO: maybe it still should be tracked?
				return;
			}
			if (thinker.reads == null) {
				thinker.reads = new HashSet<Long>();
			}
			thinker.reads.add(thought.getId());
		}
		// Update the count of reads on a thought
		thought.setNumReads(thought.getNumReads() + 1);

		// Update the count of reads for the the topics, categories and it's
		// parents
		{
			Topic topic = thought.getTopic();
			topic.setNumReads(topic.getNumReads() + 1);
			for (Category category : topic.getCategories()) {
				category.setDirectNumThoughtReads(category
						.getDirectNumThoughtReads() + 1);
				do {
					category.setNumReads(category.getNumReads() + 1);
					category = category.getParent();
				} while (category != null);
			}
		}
		// Update the count of reads for the tags
		{
			if (thought.getAppliedTags() != null) {
				for (Long tagDefId : thought.getAppliedTags().keySet()) {
					TagDef tagDef = this.tags.get(tagDefId);
					do {
						tagDef.setNumReads(tagDef.getNumReads() + 1);
						tagDef = tagDef.getParent();
					} while (tagDef != null);
				}
			}
		}
	}

	public boolean canAddTagToThought(Thinker thinker, Thought thought,
			TagDef tagDef) {
		return thinker.getTagsByThought() == null
				|| thinker.getTagsByThought().get(tagDef.getId()) == null
				|| !thinker.getTagsByThought().get(tagDef.getId())
						.getThoughtIds().contains(thought.getId());
	}

	public void addTag(Thought thought, TagDef tagDef, Thinker thinker) {

		// Track that Thinker used this Tag on This thought
		if (thinker.getTagsByThought() == null) {
			thinker.setTagsByThought(new HashMap<Long, TagThinker>());
		}
		if (thinker.getTagsByThought().get(tagDef.getId()) == null) {
			thinker.getTagsByThought().put(tagDef.getId(),
					new TagThinker(thinker, tagDef, thought));
		} else {
			if (thinker.getTagsByThought().get(tagDef.getId()).getThoughtIds()
					.contains(thought.getId())) {
				Window.alert("You have allready tagged this thought with '"
						+ tagDef.getName() + "'");
				return;
			}
			thinker.getTagsByThought().get(tagDef.getId()).addThought(thought);
		}

		// Create the thought counts in Tag Definitions
		if (tagDef.thoughts == null) {
			tagDef.thoughts = new ArrayList<Thought>();
		}
		tagDef.thoughts.add(thought);
		TagDef tagDefForThoughtCount = tagDef;
		do {
			tagDefForThoughtCount.setNumThoughts(tagDefForThoughtCount
					.getNumThoughts() + 1);
			tagDefForThoughtCount = tagDefForThoughtCount.getParent();
		} while (tagDefForThoughtCount != null);

		// Update the # of Tags by a given TagDef to this Thought
		HashMap<Long, TagThought> appliedTags = thought.getAppliedTags();
		if (appliedTags == null) {
			appliedTags = new HashMap<Long, TagThought>();
			thought.setAppliedTags(appliedTags);
		}
		TagThought tagThought = appliedTags.get(tagDef.getId());
		if (tagThought == null) {
			tagThought = new TagThought(thought, tagDef);
			setRandomId(tagThought);
			appliedTags.put(tagDef.getId(), tagThought);
		}
		thought.setNumTaggings(thought.getNumTaggings() + 1);
		tagThought.setCount(tagThought.getCount() + 1);

		// Update the count of taggings for the category and it's parents
		{
			Topic topic = thought.getTopic();
			topic.setNumTaggings(topic.getNumTaggings() + 1);
			for (Category category : topic.getCategories()) {
				category.setDirectNumTaggings(category.getDirectNumTaggings() + 1);
				do {
					category.setNumTaggings(category.getNumTaggings() + 1);
					category = category.getParent();
				} while (category != null);
			}
		}

		// Historical tracking of tags
		{
			Tag tag = new Tag(tagDef, thought, thinker);
			ArrayList<Tag> instancesOfTag = tagInstances.get(tagDef.getId());
			if (instancesOfTag == null) {
				instancesOfTag = new ArrayList<Tag>();
				tagInstances.put(tagDef.getId(), instancesOfTag);
			}
			instancesOfTag.add(tag);
		}
	}

	private void createCategories() {

		rootCategory = new Category("Root Category");
		setId(rootCategory);

		Category travel = addCategory(rootCategory.addChild("Travel"));
		Category europe = addCategory(travel.addChild("Europe"));
		addCategory(travel.addChild("Mexico"));

		addCategory(europe.addChild("Germany"));
		addCategory(europe.addChild("Italy"));
		addCategory(europe.addChild("Iberian Peninsula"));
		// With thoughts
		Category family = addCategory(rootCategory.addChild("Family"));

		Category startingAFamily = addCategory(family
				.addChild("Starting A Family"));
		addCategory(startingAFamily.addChild("Proposing"));

		Category children = addCategory(family.addChild("Children"));
		addCategory(children.addChild("Getting ready for children"));
		addCategory(children.addChild("Child Development"));
		addCategory(children.addChild("Grandchildren"));

		Category spouses = addCategory(family.addChild("Spouses"));
		addCategory(spouses.addChild("Husbands"));
		addCategory(spouses.addChild("Wifes"));

		Category siblings = addCategory(family.addChild("Siblings"));
		addCategory(siblings.addChild("Sisters"));
		addCategory(siblings.addChild("Brothers"));

		Category parents = addCategory(family.addChild("Parents"));
		addCategory(parents.addChild("My Parents"));
		addCategory(parents.addChild("My Grandparents"));
		addCategory(parents.addChild("Parents-In-Law"));
		addCategory(parents.addChild("Grandparents-In-Law"));

		Category extendedFamily = addCategory(family.addChild("Cousins"));
		addCategory(extendedFamily.addChild("Nieces and Nephews"));
		addCategory(extendedFamily.addChild("Aunts and Uncles"));

		Category design = addCategory(rootCategory.addChild("Design"));
		addCategory(design.addChild("Human Computer Interaction"));
		addCategory(design.addChild("Graphics Design"));

		Category sports = addCategory(rootCategory.addChild("Sports"));
		addCategory(sports.addChild("American Football"));
		addCategory(sports.addChild("Soccer"));

		addCategory(rootCategory.addChild("Economics"));
		addCategory(rootCategory.addChild("Politics"));
		addCategory(rootCategory.addChild("Programming"));

		// With one placeholder
		addCategory(rootCategory.addChild("Philosophy"));
		addCategory(rootCategory.addChild("Movies"));
		addCategory(rootCategory.addChild("Shopping"));
	}

	private Topic addToTopic(Category owningCategory, String name,
			Thought thought) {
		Topic topic = topics.get(name);
		if (topic == null) {
			topic = addTopic(owningCategory, name, null);
		}
		topic.setNumThoughts(topic.getNumThoughts() + 1);
		topic.thoughts.add(thought);
		thought.topic = topic;
		return topic;
	}

	private Thought addThought(String title, String synposis, String text,
			Thinker thinker, String categoryName, String topicName) {
		return addThought(title, synposis, text, thinker, categoryName,
				topicName, 1);
	}

	private Thought addThought(String title, String synposis, String text,
			Thinker thinker, String categoryName, String topicName,
			int readMultiplier) {
		Category category = categories.get(categoryName);
		Thought thought = new Thought(title, synposis, text, thinker.getId());
		Topic topic = addToTopic(category, topicName, thought);
		addThought(thought, thinker, topic, readMultiplier);

		addTagsRandomly(thought, thinker);
		addReferecesRandomly(thought);

		return thought;
	}

	private void addTagsRandomly(Thought thought, Thinker thinker) {
		int totalNumTags = this.tags.size();
		int numThinkers = Random.nextInt(2) + 1;
		for (Thinker aThinker : this.thinkers.values()) {
			if (numThinkers < 1) {
				break;
			}
			if (aThinker != thinker) {
				int numTags = Random.nextInt(8) + 1;
				for (int i = 0; i < numTags; i++) {
					int tagIndex = Random.nextInt(totalNumTags);
					TagDef tagDef = this.allTagList.get(tagIndex);
					if (!canAddTagToThought(aThinker, thought, tagDef)) {
						i--;
						continue;
					}
					addTag(thought, tagDef, aThinker);
					do {
						tagDef.setNumReads(tagDef.getNumReads()
								+ thought.getNumReads());
						tagDef = tagDef.getParent();
					} while (tagDef != null);
				}

				numThinkers--;
			}
		}
	}

	private void addReferecesRandomly(Thought thought) {
		int numReferencess = Random.nextInt(4);
		for (int i = 0; i < numReferencess; i++) {
			int thoughtIndex = Random.nextInt(this.allThoughtList.size());
			Thought referencingThoughts = this.allThoughtList.get(thoughtIndex);
			if (thought != referencingThoughts) {
				addThoughtReference(referencingThoughts, thought);
			}
		}
	}

	public Thought addThought(Thought thought, Thinker thinker, Topic topic,
			int readMultiplier) {
		thought.setPublishedDate(random());
		thought.setPublished(true);
		thought.setThinker(thinker);
		Long numReads = (new Double(Math.random() * 10)).longValue()
				* readMultiplier;
		thought.setNumReads(numReads);
		setId(thought);

		if (thinker.thoughtsCronologically == null) {
			thinker.thoughtsCronologically = new TreeSet<Thought>(
					newFirstComparator);
		}
		thinker.thoughtsCronologically.add(thought);

		thinker.getThoughtsCronologically().add(thought);

		thoughts.put(thought.getId(), thought);
		for (Category category : topic.getCategories()) {
			category.setDirectNumThoughts(category.getDirectNumThoughts() + 1);
			category.setDirectNumThoughtReads(category
					.getDirectNumThoughtReads() + 1);
			do {
				category.setNumThoughts(category.getNumThoughts() + 1);
				category.setNumReads(category.getNumReads() + numReads);
				category = category.getParent();
			} while (category != null);
		}
		this.allThoughtList.add(thought);
		return thought;
	}

	public Thought getThought(Long id) {
		return thoughts.get(id);
	}

	private void createTags() {
		rootTag = new TagDef("Root Tag");
		setId(rootTag);

		TagDef political = addTag(rootTag.addChild("Political"));
		addTag(political.addChild("Left Wing"));
		addTag(political.addChild("Liberal"));
		addTag(political.addChild("Centrist"));
		addTag(political.addChild("Conservative"));
		addTag(political.addChild("Right Wing"));

		TagDef informative = addTag(rootTag.addChild("Informative"));
		addTag(informative.addChild("Ingenuous"));
		addTag(informative.addChild("Outspoken"));
		addTag(informative.addChild("Interesting"));
		addTag(informative.addChild("Thoughtful"));
		addTag(informative.addChild("Thorough"));
		addTag(informative.addChild("Instructive"));
		addTag(informative.addChild("Educational"));
		addTag(informative.addChild("Rehashed"));

		TagDef emotional = addTag(rootTag.addChild("Emotional"));
		addTag(emotional.addChild("Compassionate"));
		addTag(emotional.addChild("Heartfelt"));
		addTag(emotional.addChild("Compassionate"));
		addTag(emotional.addChild("Compassionate"));
		addTag(emotional.addChild("Insensitive"));

		TagDef subjective = addTag(rootTag.addChild("Subjective"));
		addTag(subjective.addChild("Genuine"));
		addTag(subjective.addChild("Frank"));
		addTag(subjective.addChild("Cordial"));
		addTag(subjective.addChild("Sincere"));
		addTag(subjective.addChild("Incincere"));
		addTag(subjective.addChild("Candid"));
		addTag(subjective.addChild("Biased"));
		addTag(subjective.addChild("Honest"));
		addTag(subjective.addChild("Direct"));
	}

	private TagDef addTag(TagDef tag) {
		setId(tag);
		tags.put(tag.getId(), tag);
		allTagList.add(tag);
		return tag;
	}

	private Category addCategory(Category category) {
		categories.put(category.getName(), category);
		allCategoryList.add(category);
		setId(category);
		return category;
	}

	private static long NEXT_ID = 1L;

	public static void setId(DatastoreObject datastoreObject) {
		datastoreObject.setId(++NEXT_ID);
	}

	private static long NEXT_RANDOM_ID = 1000000L;

	public static void setRandomId(DatastoreObject datastoreObject) {
		datastoreObject.setId(++NEXT_RANDOM_ID);
	}

	private Date random() {
		return new Date(now.getTime() - Random.nextInt(1000000000));
	}

	@SuppressWarnings("deprecation")
	private void createThinkers() {
		Date joinedOn = new Date();
		joinedOn.setMonth(joinedOn.getMonth() - 5);
		joeSixpack = new Thinker("JoeSixpack@google.com", "joeSixpack", "blah",
				joinedOn);
		thinkers.put(joeSixpack.getThinkerId(), joeSixpack);
		setId(joeSixpack);
		thinkersById.put(joeSixpack.getId(), joeSixpack);

		joinedOn = new Date();
		joinedOn.setMonth(joinedOn.getMonth() - 3);
		johnSmith = new Thinker("JohnSmith@google.com", "johnSmith", "blah",
				joinedOn);
		thinkers.put(johnSmith.getThinkerId(), johnSmith);
		setId(johnSmith);
		thinkersById.put(johnSmith.getId(), johnSmith);

		joinedOn = new Date();
		joinedOn.setMonth(joinedOn.getMonth() - 1);
		jamesJohnson = new Thinker("JamesJohnson@google.com", "jamesJohnson",
				"blah", joinedOn);
		thinkers.put(jamesJohnson.getThinkerId(), jamesJohnson);
		setId(jamesJohnson);
		thinkersById.put(jamesJohnson.getId(), jamesJohnson);
	}

	public Category searchThoughts(String text) {
		Category searchResults = new Category("Search Results");

		String[] searchTerms = text.split(" ");

		for (Thought thought : this.thoughts.values()) {
			for (String searchTerm : searchTerms) {
				if (searchTerm.trim().length() > 0) {
					searchTerm = searchTerm.toLowerCase();
					if (thought.getTitle().toLowerCase().contains(text)
							|| thought.getSynopsis().toLowerCase()
									.contains(text)
							|| thought.getText().toLowerCase().contains(text)) {
						searchResults.thoughts.add(thought);
					}
				}
			}
		}

		return searchResults;
	}

	public void addThoughtReference(Thought currentThought,
			Thought referencedThought) {

		// Update the count of references for the category and it's parents
		{

			Topic topic = currentThought.getTopic();
			topic.setNumReferences(topic.getNumReferences() + 1);
			for (Category category : topic.getCategories()) {
				category.setDirectNumReferences(category
						.getDirectNumReferences() + 1);
				do {
					category.setNumReferences(category.getNumReferences() + 1);
					category = category.getParent();
				} while (category != null);
			}
		}

		if (currentThought.getReferencedThoughts() == null) {
			currentThought.setReferencedThoughts(new ArrayList<Thought>());
		}
		currentThought.getReferencedThoughts().add(referencedThought);

		if (referencedThought.getReferencingThoughts() == null) {
			referencedThought.setReferencingThoughts(new ArrayList<Thought>());
		}
		referencedThought.getReferencingThoughts().add(currentThought);
	}

	public Topic addTopic(Category initialCategory, String name,
			String description) {
		Topic topic = new Topic(name);
		setId(topic);
		topic.setCreatedDate(new Date());
		if (description == null) {
			description = "";
		}
		topic.setDescription(description);
		topic.getCategories().add(initialCategory);
		initialCategory.getTopics().add(topic);
		topics.put(name, topic);
		allTopicList.add(topic);
		return topic;
	}
}
